;(function( $, window, document, undefined ) {

    // Enable cross-domain calls in IE
    jQuery.support.cors = true;

//    jQuery.ajaxSetup({
//        crossDomain: true,
//        xhrFields: {
//            withCredentials: true
//        }
//    });

    // Enable cross-domain calls between containers and gadgets
    document.domain = window.location.hostname;

    if (gadgets && gadgets.config && gadgets.rpc) {
        var rpcconf = gadgets.config.get('rpc');
        rpcconf.disableForceSecure = true;
        gadgets.config.init('rpc', rpcconf);
    }
    if (gadgets && gadgets.pubsub2router) {
        gadgets.pubsub2router.init({
            onSubscribe: function(topic, container) { return true; }, // return false to reject the request.
            onUnsubscribe: function(topic, container) { },
            onPublish: function(topic, data, pcont, scont) { return true; } // return false to reject the request.
        });
    }

    // Create an instance of the top-level Karamu object
    window.karamu = new Karamu('dashboard');
    karamu.models = Karamu.models;
    _.each(['catalog', 'preview', 'groups', 'group', 'gadget'], karamu.addController, karamu);

    if (karamu.authenticated()) {
        karamu.observe();
        karamu.fetchModel();
    } else {
        $('#login').modal('show');
        $('#login .form-login').on('submit', function(e){
            e.preventDefault();
            karamu.authenticate({
                username: $('#login .form-login input[name="username"]').val(),
                password: $('#login .form-login input[name="password"]').val(),
                expires: $('#login .form-login input[name="remember-me"]').is('checked') ? 365 : undefined,
                callback: function(){
                    $('#login').modal('hide');
                    karamu.observe();
                    karamu.fetchModel();
                }
            });
        });
    }

})( jQuery, window, document );